package com.central.apps.handler;

import cn.hutool.core.map.MapUtil;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 故障事故汇报单
 */
@Component
public class FaultreportHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;

    /**
     * 故障事故汇报单设置节点自定义审批人
     * @param app
     * @param id
     * @param flowNode
     * @param vars
     * @return
     * @throws Exception
     */
    public String addFlowCandidate(String app, Long id, FlowNode flowNode, Map<String, Object> vars) throws Exception {
        String executer = null;
        //拿到deptcode
        List<Map<String, Object>> defectreport = handlerService.findBySql("select deptcode,deptincharge from bl_faultreport where id=" + id);
        String deptcode= MapUtil.getStr(defectreport.get(0),"deptcode");
        String deptincharge= MapUtil.getStr(defectreport.get(0),"deptincharge");
        Map<String, String> map = new HashMap<>();
        map.put("sbczsh"," and p.deptcode = '" + deptcode + "' and position like '%厂长%'  ");
        map.put("gkssh"," and position = '综合管理员' ");
        map.put("zbbkzsp"," and p.deptname = '" + deptincharge + "' and position like '%科长%'  ");
        map.put("zbbfgbzsp"," and position like '%部长%' ");
        if(StringUtils.isNotBlank(map.get(flowNode.getId()))){
            //拿到username
            StringBuffer sbf = new StringBuffer("select u.username from bl_person p left join sys_user u on p.personid = u.worknumber where 1=1 " + MapUtils.getString(map, flowNode.getId()));
            List<Map<String, Object>> persons = handlerService.findBySql(sbf.toString());
            if(CollectionUtils.isNotEmpty(persons)){
                //人员以逗号隔开
                StringJoiner sj = new StringJoiner(",","","");
                for(Map<String, Object> username : persons){
                    sj.add(MapUtils.getString(username,"username"));
                }
                executer = sj.toString();
            }
        }
        return executer;
    }
}
